CONTENTS | INDEX | PREV | NEXT
malloc
NAME
malloc - allocate memory, the memory is NOT automatically cleared
SYNOPSIS
void *ptr = malloc(bytes);
size_t bytes;
FUNCTION
malloc allocates the specified number of bytes of memory. The
returned pointer is longword aligned.
malloc returns NULL if the memory could not be allocated. Note
that, unlike calloc, malloc does NOT ZERO THE MEMORY it
returns.
EXAMPLE
/*
* allocate 16 objects and fill with junk, same as calloc example
* but uses malloc instead. Note that using malloc has the
* advantage of not having to do a run time multiplication (and
* possibly not bring in _muls or _mulu from c.lib to accomplish
* this)
*/
#include <stdlib.h>
#include <assert.h>
typedef struct {
long a, b, c;
} Junk;
main()
{
Junk *jp;
jp = malloc(sizeof(Junk) * 16);
assert(jp);
setmem(jp, sizeof(Junk) * 16, 0);
{
Junk *tj = jp;
short i;
for (i = 0; i < 16; ++i, ++tj) {
tj->a = 1;
tj->b = 2;
tj->c = 3;
}
}
free(jp);
return(0);
}
INPUTS
size_t bytes; number of bytes to allocate
RESULTS
void *ptr; pointer to base of allocated memory. The memory
is not zerod.
SEE ALSO
calloc, strdup